package com.maple.exclusivesport;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * created by DESTINY on 2018/7/27
 */
public class FileTool {

    public static void bitmapToFile(Bitmap bitmap, String path) {

        File file = new File(path);
        try {
            file.createNewFile();
            FileOutputStream fileOut = new FileOutputStream(file);
            /**原始图片**/
            //bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOut);
            /**压缩图片**/
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fileOut);
            fileOut.flush();
            fileOut.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Bitmap imgPathToBitmap(String imgPath) {

        try {
            FileInputStream fis = new FileInputStream(imgPath);
            if (null != fis) {
                return BitmapFactory.decodeStream(fis);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static List<Bitmap> imgPathToBitmaps(String[] imgPath) {

        List<Bitmap> bitmaps = new ArrayList<>();
        FileInputStream fis = null;

        try {
            for (String path : imgPath) {
                if (!new File(path).exists()) {
                    continue;
                }
                fis = new FileInputStream(path);

                if (null != fis) {
                    bitmaps.add(BitmapFactory.decodeStream(fis));
                }
                //为了解决加载过多图片，内存使用过多导致app奔溃的问题，暂时只支持加载10张图片
                if (bitmaps.size() >= 10)
                    break;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return bitmaps;
    }

    public static Bitmap loadFile(String path, int reqWidth, int reqHeight) {

        Bitmap bitmap = null;

        File mFile = new File(path);

        //判读文件是否存在
        if (mFile.exists()) {
            BitmapFactory.Options mOptions = new BitmapFactory.Options();

            //设置只加载尺寸资源
            mOptions.inJustDecodeBounds = true;

            //设置资源
            //mOptions.inSampleSize = caculateInSampleSize(mOptions, reqWidth, reqHeight);
            mOptions.inPreferredConfig = Bitmap.Config.ARGB_4444;

            //bitmap = BitmapFactory.decodeFile(path, mOptions);

            //图片加载缩方处理
            coundScale(mOptions, reqWidth, reqHeight);

            //设置加载资源模式
            mOptions.inPurgeable = true;
            mOptions.inInputShareable = true;
            mOptions.inJustDecodeBounds = false;

            //设置资源
            bitmap = BitmapFactory.decodeFile(path, mOptions);

        }

        return bitmap;
    }

    public static List<Bitmap> loadFile(String[] paths, int reqWidth, int reqHeight) {

        List<Bitmap> bitmaps = new ArrayList<>();
        Bitmap bitmap = null;
        for (String path : paths) {

            File mFile = new File(path);

            //判读文件是否存在
            if (mFile.exists()) {
                BitmapFactory.Options mOptions = new BitmapFactory.Options();

                //设置只加载尺寸资源
                mOptions.inJustDecodeBounds = true;

                //设置资源
                mOptions.inSampleSize = caculateInSampleSize(mOptions, reqWidth, reqHeight);
                mOptions.inPreferredConfig = Bitmap.Config.ARGB_4444;

                bitmap = BitmapFactory.decodeFile(path, mOptions);

                //图片加载缩方处理
                //coundScale(mOptions);

                //设置加载资源模式
                mOptions.inPurgeable = true;
                mOptions.inInputShareable = true;
                mOptions.inJustDecodeBounds = false;

                //设置资源
                bitmap = BitmapFactory.decodeFile(path, mOptions);

                bitmaps.add(bitmap);
            }
        }

        return bitmaps;
    }

    /**
     * 判断文件是否存在
     * @param paths 存在路径
     * @return
     */
    public static String[] fileIsExist(String[] paths) {

        String[] existPath = new String[paths.length];
        int is = 0;
        for (int i = 0; i < paths.length; i++) {
            File file =  new File(paths[i]);

            if (!file.exists()) {
                continue;
            }

            existPath[is] = paths[i];
            is += 1;
        }

        return existPath;
    }

    public static List<String> fileIsExistToList(String[] paths) {

        List<String> existPath = new ArrayList<>();

        for (String s : paths) {
            File file =  new File(s);

            if (!file.exists()) {
                continue;
            }

            existPath.add(s);
        }

        return existPath;
    }

    public static boolean fileIsExist(String paths) {

        File file =  new File(paths);

        if (!file.exists()) {
            return false;
        }

        return true;
    }

    /**
     * 计算缩放比例，防止OOM
     *
     * @param opeions BitmapFactory.Options
     */
    public static void coundScale(BitmapFactory.Options opeions, int reqWidth, int reqHeight) {
        if (opeions != null) {
            //原图的尺寸
            int orginalWidht = opeions.outWidth;
            int orginalHieght = opeions.outHeight;

            //如果图片尺寸大于一定尺寸的时候进行缩放
            if (orginalWidht > 1280 || orginalHieght > 800) {

                //缩小倍数
                int scale = 1;

                if (orginalWidht > orginalHieght) {
                    //长图片的时候（以宽度为基准缩小）
                    scale = orginalWidht / 1280;
                } else if (orginalWidht < orginalHieght) {
                    //高图的时候（以高度为基准缩小）
                    scale = orginalHieght / 800;
                } else {
                    //正方形图的时候（以宽度为基准缩小）
                    scale = orginalWidht / 1280;
                }

                Log.i("coundScale", "coundScale: " + scale);
                opeions.inSampleSize = scale;
            }
        }
    }

    private static int caculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {

        int width = options.outWidth;
        int height = options.outHeight;
        int inSampleSize = 1;

        if (width > reqWidth || height > reqHeight) {
            int widthRadio = Math.round(width * 1.0f / reqWidth);
            int heightRadio = Math.round(height * 1.0f / reqHeight);
            inSampleSize = Math.max(widthRadio, heightRadio);
        }

        return inSampleSize;
    }
	
	
    /**
     * 圆角图片
     * @param bitmap
     * @param roundPx
     * @return
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Bitmap output = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, w, h);
        final RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }

    /**
     * 旋转图片
     * @param angle
     * @param bitmap
     * @return Bitmap
     */
    public static Bitmap rotaingImageView(int angle , Bitmap bitmap) {

        //旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        if(Constants.cameraIndex==1)
        matrix.postScale(-1,1);

        // 创建新的图片
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }


//    /**
//     * 旋转图片
//     * @param angle
//     * @param bitmap
//     * @return Bitmap
//     */
//    public static Bitmap rotaingImageView(int angle , Bitmap bitmap,int y) {
//
//
//        //旋转图片 动作
//        Matrix matrix = new Matrix();
//        matrix.postRotate(angle);
//
//        /**切割图片**/
//        int width;
//        int x;
//        try{
//
//            if(y>=50){
//                x=y-50;
//            }else {
//                x=0;
//            }
//
//            width=bitmap.getWidth()-x;
//            if(width>=333){
//                width=333;
//            }
//
//        }catch (Exception e){
//            Log.i(e.getMessage());
//            x=0;
//            width=bitmap.getWidth();
//        }
//        // 创建新的图片 y x height width
//        return Bitmap.createBitmap(bitmap, x,0, width, bitmap.getHeight(), matrix, true);
//    }
    /**
     * 删除文件夹
     *
     * @param fileName
     *            要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteF(String fileName) {

        android.util.Log.e("deleteFile==" , fileName);

        File file = new File(fileName);

        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (!file.exists() || !file.isFile()) {
            return false;
        }

        return file.delete();
    }
    /**
     * 删除单个文件
     *
     * @param fileName
     *            要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String fileName) {

        android.util.Log.e("deleteFile==" , fileName);

        File file = new File(fileName);

        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (!file.exists() || !file.isFile()) {
           return false;
        }

        return file.delete();
    }

    /**
     * 清空文件夹
     * @return
     */
    public static boolean deleteFileList(String filePath) {

        try{
            File file = new File(filePath);

            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    f.delete();
                }

                return true;
            }
        }catch (Exception e)
        {
            Log.e("FileTool",e.getMessage());
        }
        return false;
    }
    public static final String TAG = "FileTool";
    public static List<String> getFiles(String path) {
        File dir = new File(path);
        if (!dir.exists())
            return null;
        File[] files = dir.listFiles();
        if (files == null)
            return null;
        List<String> stringList = new ArrayList<>();
        for (File file : files) {
            stringList.add(file.getPath());
            android.util.Log.i(TAG, "getFiles: " + file.getPath());
            Log.i(TAG , "，获取日记文件名：" + file.getPath());
            if (stringList.size() == 2)//只拿2个日记文件
                break;
        }
        return stringList;
    }
}
